﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

namespace RemoteGacutil.Logic
{
    public class PsExecUtil
    {
        const string psExecFormat = @"{0} /accepteula \\{1} {2} {3}";
        const string directExecFormat = @"{0} {1}";
        static string psExec = "psexec";

        static PsExecUtil()
        {
            psExec = Path.Combine(Application.StartupPath, "psexec");
        }

        public static string Execute(string server, string cmd, string args)
        {
            var command = string.Format(psExecFormat, psExec, server, cmd, args);
            return ExecuteAndGetOutput(command);    
        }

        public static string LocalExecute(string cmd, string args)
        {
            var command = string.Format(directExecFormat, cmd, args);
            return ExecuteAndGetOutput(command);    
        }

        private static string ExecuteAndGetOutput(string command)
        {
            string resultFile = Path.GetTempFileName();
            string commandFile = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(resultFile) + ".bat");

            command += @" >""{0}""";
            command = string.Format(command, resultFile);
            File.WriteAllText(commandFile, command);

            ProcessStartInfo psi = new ProcessStartInfo();
            psi.FileName = commandFile;
            psi.WindowStyle = ProcessWindowStyle.Hidden;
            Process p = Process.Start(psi);
            p.WaitForExit();

            int exitCode = p.ExitCode;
            return File.ReadAllText(resultFile);            
        }


    }
}
